import { Application } from 'egg';
import * as pageFindPlugin from 'mongoose-paginate';
import { CommentsStatus, CommentsType } from '../constants/index';

export default (app: Application) => {
  const mongoose = app.mongoose;
  const ObjectId = mongoose.Schema.Types.ObjectId;
  const commentsSchema = new mongoose.Schema({
    // 贴子Id
    postId: ObjectId,
    // 评论者
    user: {
      type: ObjectId,
      required: true,
    },
    // 帖子作者ID
    authorId: ObjectId,
    // 评论/回复目标用户信息
    targetUser: {
      userId: ObjectId,
      userName: String,
      avatar: String,
    },
    // 评论者用户信息
    replayUser: {
      userId: ObjectId,
      userName: String,
      avatar: String,
    },
    // 类型(1: 评论， 2: 回复)
    type: {
      type: Number,
      enum: [ CommentsType.comment, CommentsType.reply ],
      default: CommentsType.comment,
    },
    // 评论内容
    content: String,
    // 是否被删除
    status: {
      type: Number,
      enum: [ CommentsStatus.published, CommentsStatus.deleted ],
      default: CommentsStatus.published,
    },
  }, { timestamps: { createdAt: true } });
  commentsSchema.index({ postId: 1 });
  commentsSchema.plugin(pageFindPlugin, {});
  return mongoose.model('Comments', commentsSchema);
};
